<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { CommentFindByCSID, commentAddService } from "@/api/comment.js"; // 假设这是获取评论的API
import { ElMessage } from 'element-plus';
import { userInfoService ,userInfoByNameService} from "@/api/user.js";

const route = useRoute(); //获取路由
const courseId = route.params.courseId; //获取路由参数
const comments = ref([]); //评论列表
const dataModle = ref({
  rate: "",
  content: "",
  courseId: route.params.courseId, //获取路由参数
  userId: "", //这个后端能处理
  userName: "", //这个后端也能处理
  pic: "",
  target: "", //要函数处理
  pid: "", //函数处理
});

const dialogFormVisible = ref(false); // 对话框显示状态

//获取评论列表
const fetchComments = async () => {
  try {
    const result = await CommentFindByCSID(courseId);
    const commentsWithAvatars = await Promise.all(result.data.map(async (comment) => {
      console.log('Comment:', comment); // 调试输出评论对象
      console.log('User ID:', comment.userId); // 调试输出用户ID

      const userInfo = await userInfoByNameService(comment.userName);
      console.log('User Info:', userInfo); // 调试输出用户信息

      let reviewerInfo = null;
      if (comment.reviewerId) {
        reviewerInfo = await userInfoService(comment.reviewerId);
        console.log('Reviewer Info:', reviewerInfo); // 调试输出法评人信息
      }

      return {
        ...comment,
        avatarUrl: userInfo.data.userPic ? userInfo.data.userPic : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 默认头像
        reviewerAvatarUrl: reviewerInfo ? (reviewerInfo.data.userPic ? reviewerInfo.data.userPic : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png') : null // 法评人头像
      };
    }));
    comments.value = commentsWithAvatars;
    console.log('Comments with Avatars:', commentsWithAvatars); // 调试输出处理后的评论列表
  } catch (error) {
    console.error("获取评论失败", error);
  }
};

onMounted(() => {
  fetchComments();
});

const falshDataModle = async () => {
  dataModle.value = {
    rate: "",
    content: "",
    courseId: route.params.courseId, //获取路由参数
    userId: "", //这个后端能处理
    userName: "", //这个后端也能处理
    pic: "",
    target: "", //要函数处理
    pid: "", //函数处理
  };
};

const submitComment = async () => {
  dataModle.value.courseId = route.params.courseId;
  const result = await commentAddService(dataModle.value);
  ElMessage.success(result.msg ? result.msg : "添加成功");
  falshDataModle(); //提交后，刷新评论
  fetchComments();
};

const reply = (id, userName, pid) => {
  //如果这个评论是一级评论 ，那么pid为空 
  dialogFormVisible.value = true; //显示对话框
  dataModle.value = {
    content: "",
    userId: "", //后端
    userName: "", //后端 
    target: userName,
    pid: pid ? pid : id,
    courseId: route.params.courseId, //课程id
    rate: null, //评分为空
  }; // 初始化评论对象
};

const replyConfirm = async () => {
  const result = await commentAddService(dataModle.value);
  ElMessage.success(result.msg ? result.msg : "添加成功");
  dialogFormVisible.value = false; //关闭对话框
  falshDataModle(); //提交后，刷新评论
  fetchComments();
};
</script>

<template>
  <el-card class="page-container transparent-card">
    <div class="header">
      <h1 class="title">课程评论区 请写下你宝贵的评论</h1>
    </div>
    <div class="content-center">
      <div>
        <div class="rate-container">
          <h1>请为课程打星：</h1>
          <el-rate v-model="dataModle.rate" :texts="['极差', '不太好', '普通', '好', '非常好']" show-text />
        </div>
        <div>
          <el-input type="textarea" v-model="dataModle.content" placeholder="请输入你的评论"></el-input>
          <el-button type="primary" @click="submitComment">提交</el-button>
        </div>
      </div>
    </div>
    <!-- 评论区 -->
    <div>
      <div style="
          margin: 10px 8;
          font-size: 24px;
          padding: 10px 0;
          border-bottom: 1px solid #ccc;
          text-align: left;
        ">
        评论列表
      </div>
      <div style="margin: 20px 0; text-align: left">
        <div style="padding: 10px" v-for="item in comments" :key="item.id">
          <div style="display: flex">
            <div style="width: 80px">
              <el-avatar :size="50" :src="item.avatarUrl"></el-avatar>
            </div>
            <div style="flex: 1">
              <div>{{ item.userName }} {{ item.createTime }}</div>
              <div style="margin-top: 10px; color: #000">
                {{ item.content }}
              </div>
              <div v-if="item.reviewerAvatarUrl">
                <div style="display: flex; align-items: center; margin-top: 10px;">
                  <el-avatar :size="30" :src="item.reviewerAvatarUrl" style="margin-right: 10px;"></el-avatar>
                  <span>法评人</span>
                </div>
              </div>
              <div>
                <el-rate v-model="item.rate" :texts="['极差', '不太好', '普通', '好', '非常好']" show-text disabled />
              </div>
              <div>
                <el-button type="text" @click="reply(item.pid, item.userName, item.id)"> 回复 </el-button>
                <!--回复列表-->
              </div>
              <div v-if="item.secondLevelComments && item.secondLevelComments.length"
                style="margin-left: 10px; background-color: aliceblue; padding: 10px; border-radius: 10px">
                <div v-for="sub in item.secondLevelComments" :key="sub.id">
                  <div style="padding:5px 0" class="comment-item" @click="reply(sub.id, sub.userName, sub.pid)">
                    {{ sub.userName }} <span>回复 <span style="color: cornflowerblue">@{{ sub.target }}</span>
                    <span style="color: #666; margin-left: 10px">{{ sub.content }}</span></span>
                    <span style="float: right; font-size: 13px; color: #666; margin-top:3px">{{ sub.createTime }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--secondLevelComments-->
    </div>
  </el-card>
  <el-dialog v-model="dialogFormVisible" title="回复对话框" width="500">
    <el-form :model="dataModle">
      <el-form-item label="回复内容" :label-width="formLabelWidth">
        <el-input style="height:100px" v-model="dataModle.content" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="replyConfirm">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%; //设置最小高度，保证页面不会出现滚动条
  box-sizing: border-box; //设置边框模型
}

.transparent-card {
  background-color: rgba(255, 255, 255, 0.8); /* 半透明白色背景 */
  backdrop-filter: blur(0px); /* 模糊效果 */
  border-radius: 4px; /* 圆角 */
  padding: 20px; /* 内边距 */
}

.content-center {
  text-align: center; /* 使文本内容居中 */
  margin: 0 auto; /* 使块级元素居中 */
  max-width: 600px; /* 可选：设置最大宽度 */
}

.title {
  font-size: 24px; /* 增加字体大小 */
  font-weight: bold; /* 加粗字体 */
  color: #8e2121; /* 设置字体颜色 */
  margin-bottom: 20px; /* 增加底部间距 */
  text-align: center; /* 使标题居中 */
  border-bottom: 2px solid #ccc; /* 可选：添加下划线效果 */
  padding-bottom: 10px; /* 可选：增加下划线与文本之间的间距 */
}

.rate-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
}

.comment-item:hover {
  font-weight: bold; /* 鼠标悬停时加粗 */
}
</style>